package com.gpframework.common.utils;


import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Subdivision;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class IpAddress {

    /**
     * 获取ip地址和所属地区
     * @param request
     * @return
     */
    public static Map<String, Object> getIpInfo(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("ipAddress","");
        map.put("area","");
        map.put("region","");
        String ipAddress = getIpAddr(request);
        //ipAddress = "121.32.77.242";
        if (StringUtils.isNotBlank(ipAddress)){
            map.put("ipAddress",ipAddress);
            try {
                //ip所属区域
                getIpAddress(map);
            } catch (Exception e) {
                log.error("异常信息",e);
            }
        }
        return map;
    }

    /**
     * 获取当前网络ip
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("异常信息",e);
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 根据IP地址获取地区
     * @return
     * @throws Exception
     */
    public static void getIpAddress(Map<String, Object> map){
        try {
            // 创建 GeoLite2 数据库
            //String path = IpAddress.class.getClassLoader().getResource("utils/GeoLite2-City.mmdb").getPath();
//            File database = new File(path);
            File database = new File("/root/ip_util/GeoLite2-City.mmdb");
            // 读取数据库内容
            DatabaseReader reader = new DatabaseReader.Builder(database).build();
            InetAddress address = InetAddress.getByName(map.get("ipAddress").toString());
            // 获取查询结果
            CityResponse response = reader.city(address);
            StringBuffer area = new StringBuffer();
            if (null != response){
                // 获取国家信息
                Country country = response.getCountry();
                if (null != country.getName()){
                    area.append(country.getName());
                    map.put("area",country.getName());
                }
                // 获取省份
                Subdivision subdivision = response.getMostSpecificSubdivision();
                if (null !=subdivision.getName()){
                    area.append(" " + subdivision.getName());
                }
                // 获取城市
                City city = response.getCity();
                if (null !=city.getName()){
                    area.append(" " + city.getName());
                }
                map.put("region",area.toString());
            }
        } catch (Exception e) {
            log.error("错误信息:{}",e);
        }
        if (StringUtils.isBlank(map.get("area").toString())){
            map.put("area","earth");
        }
        if (StringUtils.isBlank(map.get("region").toString())){
            map.put("region","unknown");
        }
    }
}
